package com.toidep.activities;

import java.io.File;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Canvas;
import android.os.Bundle;
import android.provider.Settings;
import android.view.MotionEvent;
import android.widget.ImageView;

import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.SlidingMenu.CanvasTransformer;
import com.toidep.R;

import android.view.KeyEvent;

import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseABSActivity;
import com.toidep.bitmaputil.ImageCache;
import com.toidep.bitmaputil.ImageCache.ImageCacheParams;
import com.toidep.bitmaputil.ImageFetcher;
import com.toidep.config.Constants;
import com.toidep.entities.AlbumEntity;
import com.toidep.entities.ArticleEntity;
import com.toidep.entities.ModelEntity;
import com.toidep.entities.VideoEntity;
import com.toidep.fragment.mains.MainFragment;
import com.toidep.fragment.mains.UserInfoFragment;
import com.toidep.fragment.others.AlbumDetailFragment;
import com.toidep.fragment.others.ModelDetailFragment;
import com.toidep.fragment.others.NewsDetailFragment;
import com.toidep.fragment.others.SearchFragment;
import com.toidep.fragment.others.VideoPlayerFragment;
import com.toidep.info.NewsDetailHolder;
import com.toidep.interfaces.DialogListener;
import com.toidep.interfaces.IFragmentRefreshable;
import com.toidep.interfaces.ResponseListener;
import com.toidep.payment.PaymentControl;
import com.toidep.preference.SharePreference;
import com.toidep.utilities.DialogUtility;
import com.toidep.utilities.NetworkUtility;
import com.toidep.utilities.StringUtility;

public class MainActivity extends BaseABSActivity {

	public MainFragment mainFragment;
	private CanvasTransformer mTransformer;
	public SlidingMenu slidingMenu;

	public ImageFetcher mImageFetcher;
	public int currentCategory = -1;

	public int fromTab;
	// Tao 1 entity dung chung de share, like, delete
	public static ModelEntity objModel = null;

	private PaymentControl paymentControl;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mTransformer = new CanvasTransformer() {
			@Override
			public void transformCanvas(Canvas canvas, float percentOpen) {
				float scale = (float) (percentOpen * 0.25 + 0.75);
				canvas.scale(scale, scale, canvas.getWidth() / 2,
						canvas.getHeight() / 2);
			}
		};

		setContentView(R.layout.activity_main);
		checkPaymentApprove();
		initImageFetcher();

		menuFragment = super.menuFragment;

		mainFragment = new MainFragment();
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.content_frame, mainFragment).commit();

		slidingMenu = super.slidingMenu;
		setSlidingActionBarEnabled(false);
		slidingMenu.setBehindScrollScale(0.0f);
		slidingMenu.setBehindCanvasTransformer(mTransformer);
		
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (mImageFetcher == null || mImageFetcher.isExistFile()) {
			initImageFetcher();
		}
		if (NetworkUtility.getInstance(this)
				.isNetworkAvailable()) {
			
		} else {
			if (this != null) {
//				Toast.makeText(activity,"not network", 5000).show();
				NetworkUtility.getInstance(MainActivity.this).showAlert();
			}
		}
	}
	public void checkPaymentApprove() {
		boolean loginStatus = SharePreference.getInstance(this).getLoginStatus();
		if (!loginStatus) {
			return;
		}
		ResponseListener response = new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void processResponse(String response) {
				// TODO Auto-generated method stub
				JSONObject obj;
				try {
					obj = new JSONObject(response);
					if (obj != null && (obj.getInt("code") == 1) && (obj.getString("payment").equalsIgnoreCase("true"))) {
						SharePreference.getInstance(MainActivity.this).putPaymentApprove(true);
						menuFragment.changeButtonLoginLabel();
					} else {
						SharePreference.getInstance(MainActivity.this).putPaymentApprove(false);
						menuFragment.changeButtonLoginLabel();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		};
		ApiController.getPaymentApprove(this, response);
	}
	/*
	 * Ham nhan gia tri tra ve tu Activity LoginScreenActivity resultCode = 0
	 * (not login) / 1 (logged in) requestCode dung de thuc hien Action truoc
	 * do, neu da login
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode > 0) {
			switch (requestCode) {
//			case Constants.REQUEST_CODE_VALID_TOKEN:
//				if (mResponlistener != null) {
//					ApiController.requestProcess(url, this, false, mResponlistener);
//				}
//				break;
			case Constants.REQUEST_CODE_REGISTER:
				checkPaymentApprove();
				menuFragment.changeButtonLoginLabel();
				break;
			case Constants.REQUEST_CODE_LOGIN:
				checkPaymentApprove();
				menuFragment.changeButtonLoginLabel();
				if (mainFragment.mCurrentFragment instanceof IFragmentRefreshable) {
					((IFragmentRefreshable)mainFragment.mCurrentFragment).refreshData();
				}
				break;
			case Constants.REQUEST_CODE_POST_COMMENT:
				checkPaymentApprove();
				menuFragment.changeButtonLoginLabel();
				postComment(post_commentType, post_comment_objId,
						post_comment_content, post_comment_responseListener);
				break;
			case Constants.REQUEST_CODE_LOGIN_FOR_PAYMENT:
				checkPaymentApprove();
				menuFragment.changeButtonLoginLabel();
				if (paymentControl != null)
					paymentControl.showDialogPaymentStart();
				
				if (mainFragment.mCurrentFragment instanceof IFragmentRefreshable) {
					((IFragmentRefreshable)mainFragment.mCurrentFragment).refreshData();
				}
				//Bug #293-start
				if(viewWaitting!=null){
					VideoPlayerFragment myFragment = mainFragment
							.getVideoPlayerFragment();

					if (myFragment == null)
						myFragment = VideoPlayerFragment
								.newInstance(viewWaitting.getId());
					else {
						myFragment.clearVideoData();
						myFragment.setVideoId(viewWaitting.getId());
						myFragment.getVideoDetail();
					}
					viewWaitting = null;
					mainFragment.openFragmentScreen(myFragment, null);
					
				}
				
				break;
				
			case Constants.REQUEST_CODE_LOGIN_FOR_VIEW_ALBUM:
				checkPaymentApprove();
				menuFragment.changeButtonLoginLabel();
				if (mainFragment.mCurrentFragment instanceof IFragmentRefreshable) {
					((IFragmentRefreshable)mainFragment.mCurrentFragment).refreshData();
				}
				openDetailAlbum(albumFix293);
				break;
				//Bug #293-end
				
			}
		}
	}

	@Override
	public void onBackPressed() {
		if (mainFragment != null)
			mainFragment.onBackPressed(false);
	}

	private DialogListener dialogListener = new DialogListener() {

		@Override
		public void after() {
			if (slidingMenu.isMenuShowing())
				toggle(null);
		}
	};

	public void doClick(int id) {
		switch (id) {
		case R.id.layoutButtonHome:
			if (currentCategory == Constants.CATEGORY_HOME) {
				if (slidingMenu.isMenuShowing())
					toggle(null);
				return;
			}
			mainFragment.openFragmentScreen(Constants.CATEGORY_HOME,
					dialogListener);
			break;
		case R.id.layoutButtonFree:
			if (currentCategory == Constants.CATEGORY_FREE) {
				if (slidingMenu.isMenuShowing())
					toggle(null);
				return;
			}
			mainFragment.openFragmentScreen(Constants.CATEGORY_FREE,
					dialogListener);
			break;
		case R.id.layoutButtonUpdate:
			if (currentCategory == Constants.CATEGORY_UPDATE) {
				if (slidingMenu.isMenuShowing())
					toggle(null);
				return;
			}
			mainFragment.openFragmentScreen(Constants.CATEGORY_UPDATE,
					dialogListener);
			break;
		case R.id.layoutButtonModel:
		case R.id.layoutCategoryModel:
			if (currentCategory == Constants.CATEGORY_MODEL) {
				if (slidingMenu.isMenuShowing())
					toggle(null);
				return;
			}
			mainFragment.openFragmentScreen(Constants.CATEGORY_MODEL,
					dialogListener);
			break;
		case R.id.layoutButtonVideo:
		case R.id.layoutCategoryVideo:
			if (currentCategory == Constants.CATEGORY_VIDEO) {
				if (slidingMenu.isMenuShowing())
					toggle(null);
				return;
			}
			mainFragment.openFragmentScreen(Constants.CATEGORY_VIDEO,
					dialogListener);
			break;
		case R.id.layoutButtonAlbum:
		case R.id.layoutCategoryAlbum:
			if (currentCategory == Constants.CATEGORY_ALBUM) {
				if (slidingMenu.isMenuShowing())
					toggle(null);
				return;
			}
			mainFragment.openFragmentScreen(Constants.CATEGORY_ALBUM,
					dialogListener);
			break;
		case R.id.layoutButtonIntro:
			if (currentCategory == Constants.CATEGORY_HOME_INTRO) {
				if (slidingMenu.isMenuShowing())
					toggle(null);
				return;
			}
			mainFragment.openFragmentScreen(Constants.CATEGORY_HOME_INTRO,
					dialogListener);
			break;
		case R.id.layoutButtonNews:
			if (currentCategory == Constants.CATEGORY_NEWS) {
				if (slidingMenu.isMenuShowing())
					toggle(null);
				return;
			}
			mainFragment.openFragmentScreen(Constants.CATEGORY_NEWS,
					dialogListener);
			break;
		// case R.id.layoutButtonStory:
		// if (currentCategory == Constants.CATEGORY_STORY) {
		// if (slidingMenu.isMenuShowing())
		// toggle(null);
		// return;
		// }
		// mainFragment.openFragmentScreen(Constants.CATEGORY_STORY,
		// dialogListener);
		// break;
		// case R.id.layoutButtonEvent:
		// if (currentCategory == Constants.CATEGORY_EVENT) {
		// if (slidingMenu.isMenuShowing())
		// toggle(null);
		// return;
		// }
		// mainFragment.openFragmentScreen(Constants.CATEGORY_EVENT,
		// dialogListener);
		// break;
	
		case R.id.layoutButtonRegister:
			Intent intent1 = new Intent(this, RegisterActivity.class);
			
			startActivityForResult(intent1, Constants.REQUEST_CODE_REGISTER);
			break;
		case R.id.layoutButtonLogin:
			Intent intent = new Intent(this, LoginActivity.class);

			startActivityForResult(intent, Constants.REQUEST_CODE_LOGIN);
			break;
		case R.id.layoutButtonLogout:
			SharePreference sharePreference = SharePreference.getInstance(this);
			boolean loginStatus = sharePreference.getLoginStatus();
			if (loginStatus) {
				// 18-05-2014 Bugs #301 start.
				sharePreference.clearInfoUser();
				// 18-05-2014 End.
				sharePreference.putLoginStatus(false);
				menuFragment.changeButtonLoginLabel();
				// neu man hinh hien tai la man hinh user info thi chuyen ve man
				// hinh truoc do
				if (currentCategory == Constants.CATEGORY_USER_INFO) {
					mainFragment.openFragmentScreen(Constants.CATEGORY_HOME,
							dialogListener);
				} else {
					if (mainFragment.mCurrentFragment instanceof IFragmentRefreshable) {
						((IFragmentRefreshable)mainFragment.mCurrentFragment).refreshData();
					}
				}
			}
			break;
		case R.id.layoutButtonPayment:
			(new PaymentControl(this)).showDialogPaymentStart();
			break;
		case R.id.layoutButtonUserInfo:
			loginStatus = SharePreference.getInstance(this).getLoginStatus();
			if (loginStatus) {
				if (currentCategory == Constants.CATEGORY_USER_INFO) {
					if (slidingMenu.isMenuShowing())
						toggle(null);
					return;
				}
				mainFragment.openFragmentScreen(Constants.CATEGORY_USER_INFO,
						dialogListener);
			}
			break;
		case R.id.buttonSearch:
			if (currentCategory == Constants.CATEGORY_SEARCH) {
				if (slidingMenu.isMenuShowing())
					toggle(null);
				return;
			}
			mainFragment.openFragmentScreen(Constants.CATEGORY_SEARCH,
					dialogListener);
			break;
		}
	}

	public void openLeftMenu() {
		if (slidingMenu.isMenuShowing() == false) {
			slidingMenu.showMenu();
		}
	}

	private void initImageFetcher() {
		int mImageThumbSize = 70;
		File mHttpCacheDir = ImageCache.getDiskCacheDir(this,
				Constants.HTTP_CACHE_DIR);

		if (mHttpCacheDir == null) {
			DialogUtility.showDialogAlert(this, "",
					getString(R.string.text_alert_full_memory),
					getString(R.string.label_close), null);
		}

		ImageCacheParams cacheParams = new ImageCacheParams(this,
				Constants.IMAGE_CACHE_DIR);
		// Set memory cache to 25% of mem class
		cacheParams.setMemCacheSizePercent(this, 0.25f);

		mImageFetcher = new ImageFetcher(this, mImageThumbSize, mHttpCacheDir);
		mImageFetcher.addImageCache(getSupportFragmentManager(), cacheParams);

		// try {
		// loadingBitmapList = BitmapFactory.decodeResource(getResources(),
		// R.drawable.bg_load_collection);
		// } catch (Exception e) {
		// // TODO: handle exception
		// }
	}

	public void clearFiles() {
		if (mImageFetcher != null) {
			mImageFetcher.clearFiles();
		}
	}

	public void closeCache() {
		if (mImageFetcher != null) {
			mImageFetcher.closeCache();
		}
	}

	public void clearMemmoryCache() {
		if (mImageFetcher != null) {
			mImageFetcher.clearMemoryCache();
		}
	}

	public void lockSlidingMenu(boolean isEnable) {
		try {
			slidingMenu.setSlidingEnabled(isEnable);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private int post_commentType;
	private String post_comment_objId, post_comment_content;
	private ResponseListener post_comment_responseListener;

	/**
	 * Post Comment
	 * 
	 * @param commentType
	 *            1: Model | 2: Album | 3: Video
	 * @param objId
	 *            id cua doi duoc comment (Model, Album, Video)
	 * @param comment
	 * @param responseListener
	 */
	public void postComment(int commentType, String objId, String comment,
			ResponseListener responseListener) {
		this.post_commentType = commentType;
		this.post_comment_objId = objId;
		this.post_comment_content = comment;
		this.post_comment_responseListener = responseListener;

		boolean loginStatus = SharePreference.getInstance(this)
				.getLoginStatus();
		if (!loginStatus) {
			startActivityForResult(new Intent(this, LoginActivity.class),
					Constants.REQUEST_CODE_POST_COMMENT);
		} else {
			ApiController.postComment(this, commentType, objId, comment,
					responseListener);
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		mainFragment.onTouch(event);
		return false;
	}

	public void freeze() {
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
	}

	public void unfreeze() {
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
	}

	/************** Until Methods ***************/
	public void loadImage(ImageView imageView, String imageUrl, int widthImage,
			int heightImage, int widthImageView, int heightImageView) {
		imageUrl = StringUtility.resizeImageUrl(imageUrl, widthImage,
				heightImage);
		try {
			mImageFetcher.loadImage(imageUrl, imageView, null, widthImageView,
					heightImageView, null);
		} catch (Exception e) {
		}
	}

	/************** Until Methods End ***************/

	/************** Other Methods ***************/
	public void openDetailModel(String id) {
		ModelDetailFragment myFragment = ModelDetailFragment.newInstance(id);
		mainFragment.openFragmentScreen(myFragment, null);
	}

	public void openDetailAlbum(final AlbumEntity albumEntity) {
		ApiController.getAlbumDetail(this, albumEntity.getId(),
				new ResponseListener() {

					@Override
					public void processResponse(int inintstall) {
						// TODO Auto-generated method stub

					}

					private void openFragment() {
						AlbumDetailFragment myFragment = AlbumDetailFragment
								.newInstance(albumEntity.getId(),
										albumEntity.getTotalView());
						mainFragment.openFragmentScreen(myFragment, null);
					}

					@Override
					public void processResponse(String response) {
						if (response != null && response != "") {
							try {
								JSONObject jsonObject = new JSONObject(response);
								if (jsonObject != null) {
									int code = ParseJSON.getIntValue(
											jsonObject,
											Constants.PARAM_RESPONSE_CODE);
									if (code > 0) {
										openFragment();
									} else {
										PaymentControl paymentControl = new PaymentControl(
												MainActivity.this);
										paymentControl
												.startPayment(new ResponseListener() {

													@Override
													public void processResponse(
															int inintstall) {
														if (inintstall == -1) {
															return;
														} else if (inintstall == 1) {
															openFragment();
														}
													}

													@Override
													public void processResponse(
															String response) {
													}
												});
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
								return;
							}
						}
					}
				});
	}
	private VideoEntity viewWaitting;
	public void openDetailVideo(final VideoEntity videoEntity) {
		ApiController.getVideoDetail(this, videoEntity.getId(),
				new ResponseListener() {

					@Override
					public void processResponse(int inintstall) {
						// TODO Auto-generated method stub

					}

					private void openFragment() {
						//TODO: encounter a bug that not transition fragment when use case search video.
						VideoPlayerFragment myFragment = mainFragment
								.getVideoPlayerFragment();

						if (myFragment == null)
							myFragment = VideoPlayerFragment
									.newInstance(videoEntity.getId());
						else {
							myFragment.clearVideoData();
							myFragment.setVideoId(videoEntity.getId());
							myFragment.getVideoDetail();
						}

						mainFragment.openFragmentScreen(myFragment, null);
					}

					@Override
					public void processResponse(String response) {
						if (response != null && response != "") {
							try {
								JSONObject jsonObject = new JSONObject(response);
								if (jsonObject != null) {
									int code = ParseJSON.getIntValue(
											jsonObject,
											Constants.PARAM_RESPONSE_CODE);
									if (code > 0) {
										openFragment();
									} else {
										viewWaitting = videoEntity;
										PaymentControl paymentControl = new PaymentControl(
												MainActivity.this);
										paymentControl
												.startPayment(new ResponseListener() {

													@Override
													public void processResponse(
															int inintstall) {
														if (inintstall == -1) {
															return;
														} else if (inintstall == 1) {
															openFragment();
														}
													}

													@Override
													public void processResponse(
															String response) {
													}
												});
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
								return;
							}
						}
					}
				});
	}

	public void openDetailArticle(ArrayList<ArticleEntity> listFeaturedNews,
			int type, int position) {
		try {
			NewsDetailHolder.setListNewDetail(listFeaturedNews);
			NewsDetailHolder.setCurrentPosition(position);

			mainFragment.openFragmentScreen(
					NewsDetailFragment.newInstance(type), null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void openSearchFragmen(String keyword, int tabView,
			boolean isSearchFollowTag) {
		SearchFragment myFragment = SearchFragment.newInstance(keyword,
				tabView, isSearchFollowTag);
		mainFragment.openFragmentScreen(myFragment, null);
	}

	/************** Other Methods End ***************/

	// Bug #220 - start
	public boolean checkUserLogon() {
		boolean loginStatus = SharePreference.getInstance(this)
				.getLoginStatus();
		if (!loginStatus) {
			Intent intent = new Intent(this, LoginActivity.class);
			startActivityForResult(intent, Constants.REQUEST_CODE_LOGIN);
			return false;
		}
		return true;
	}
	// Bug #220 - end
	
	//Bug #293-start
	private AlbumEntity albumFix293;
	public boolean checkUserLogonFix293(AlbumEntity albumEntity ) {
		boolean loginStatus = SharePreference.getInstance(this)
				.getLoginStatus();
		if (!loginStatus) {
			Intent intent = new Intent(this, LoginActivity.class);
			startActivityForResult(intent, Constants.REQUEST_CODE_LOGIN_FOR_VIEW_ALBUM);
			albumFix293 = albumEntity;
			return false;
		}
		return true;
	}
	//Bug #293-end
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		 if (mainFragment != null) {
			 if (mainFragment.mCurrentFragment.onKeyDown(event)){
				 return true;
			 } else {
				 
				 return super.onKeyDown(keyCode, event);
			 }
		 } else {
			 return super.onKeyDown(keyCode, event);
		 }
	}
	
	public void login(){
		Intent intent = new Intent(this, LoginActivity.class);
		startActivityForResult(intent, Constants.REQUEST_CODE_LOGIN);
	}
	
	private ResponseListener mResponlistener;
	private String url;
	public void setResponlistener(ResponseListener l, String url) {
		mResponlistener = l;
		this.url = url;
	}
}
